﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;
using System.Windows.Forms;
using Crude.VisualStudioAddin.BuildEngine;

namespace Crude.VisualStudioAddin.Actions
{
    class PublishAllLocalAction : BaseSolutionAction
    {
        public override string Name
        {
            get { return "PublishAllLocal"; }
        }

        public override string Caption
        {
            get { return "Publish All  Local"; }
        }

        public override string Tooltip
        {
            get { return "Publish all the crude projects to the local repository"; }
        }

        public override void ExecuteAction(EnvDTE80.DTE2 applicationObject)
        {
            IList<Project> projects = new List<Project>();

            foreach (Project project in applicationObject.Solution.Projects)
            {
                if (!string.IsNullOrEmpty(project.FullName))
                {
                    Core.Project crudeProject = new Core.Project(project.FullName);

                    if (crudeProject.IsImportLineExisted())
                    {
                        projects.Add(project);
                    }
                }
            }

            bool builtAllProjects = true;

            StringBuilder failedToBuildProjects = new StringBuilder();
            failedToBuildProjects.AppendLine("Failed to build the following projects:");
            failedToBuildProjects.AppendLine();

            IList<string> builtProjects = new List<string>();

            foreach (Project project in projects)
            {
                applicationObject.Solution.SolutionBuild.BuildProject(
                    applicationObject.Solution.SolutionBuild.ActiveConfiguration.Name, project.UniqueName, true);

                if (applicationObject.Solution.SolutionBuild.LastBuildInfo > 0)
                {
                    builtAllProjects = false;
                    failedToBuildProjects.AppendLine(project.Name);
                }
                else
                {
                    builtProjects.Add(project.FullName);
                }
            }

            failedToBuildProjects.AppendLine();
            failedToBuildProjects.AppendLine("Do you want to continue and publish the other projects?");

            if (builtProjects.Count > 0 && (builtAllProjects || MessageBox.Show(failedToBuildProjects.ToString(), "Crude",
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes))
            {
                Engine.Instance.Build(builtProjects, "PublishLocal", "Publish project to local repository");
            }
        }
    }
}
